import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { routerRedux, Route, Switch } from 'dva/router';
import Media from 'react-media';
import AntdDatePicker from '@/components/AntdDatePicker';
import FileImport from '@/components/FileImport';
import SearchSelect from '@/components/SearchSelect';
import { columns1, columnsBillNo } from '@/pages/Common/common';
import AdButton from '@/components/AdButton';
import { codes } from './utils';
import AdSelect from '@/components/AdSelect';
import AntdFormItem from '@/components/AntdFormItem';
const dateFormat = 'YYYY-MM-DD';
import { Form, Input, Select, DatePicker, Button, Modal, Badge } from 'antd';
import StandardTable from '@/components/StandardTable';
import FileReader from '@/components/FileReader';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import OilTetails from './OilDetails';
import { oilBillStateList, billStateOnlyReadList, allDictList } from '@/utils/constans';
import SelectForm from '@/components/SelectForm';
import ManageList from '@/components/ManageList';
import TableButtons from '@/components/TableButtons';
import RightDraw from '@/components/RightDraw';
import AdSearch from '@/components/AdSearch';
import prompt from '@/components/Prompt';
import { vitifyCheck, queryDict, renderTableAdSelect, formateDateToMin } from '@/utils/common';
import { number } from 'prop-types';


const dateFormatByM = 'YYYY-MM';
const { MonthPicker } = DatePicker;

const FormItem = Form.Item;
const { Option } = Select;
const confirm = Modal.confirm;

@ManageList
@connect(({ tmsOil, common, loading, component }) => ({
    tmsOil,
    ownCompany: common.ownCompany,
    loading: loading.effects['tmsOil/selectList'],
    dictObject: component.dictObject,
    searchValue: component.searchValue,
}))
@Form.create()
export default class OilList extends Component {
    state = {
        updateModalVisible: false,
        expandForm: false,
        stepFormValues: {},
        visible: false,
        checkId: '',
        checkIds: [],
        formValues: {},
        selectedRows: [],
        cars: [],
        billNos: [],
        isBillStatus: '',
        detailsStatus: '',
        visibleFile: false,
        isRefresh:false,
    };
    className = 'OilList';

    componentDidMount() {
        this.getSelectList();
    }
    componentWillMount() {
        // 查询字典项
        const allDict = [allDictList.currencyType, allDictList.saleCompany, allDictList.oilType];
        queryDict({ props: this.props, allDict });
    }
    columns = [
        {
            title: '单据号',
            dataIndex: 'oilNo',
            render: (text, record) => (
                <AdButton
                    mode="a"
                    onClick={() => this.showDetail( record.id, record)}
                    text={text}
                    code={codes.showDetail}
                />
            ),
            fixed: this.props.isMobile ? false : true,
        },
        {
            title: '状态',
            dataIndex: 'billStatus',
            render: (text, record) => (
                <AdSelect
                    onlyRead={true}
                    value={text ? text : record.status}
                    data={billStateOnlyReadList}
                />
            ),
            width: 100,
        },
        {
            title: '主车牌',
            dataIndex: 'cartPlateNo',
        },
        {
            title: '所属公司',
            dataIndex: 'ownCompanyName',
            width: 250,
            render: text => <span title={text}>{text}</span>,
        },
        {
            title: '行车档案号',
            dataIndex: 'archivesNo',

            render: text => <span title={text}>{text}</span>,
        },
        {
            title: '结算周期',
            dataIndex: 'settlementDate',

            render: text => <span title={text}>{text}</span>,
        },
        {
            title: '加油时间',
            dataIndex: 'oilTime',
        },
        {
            title: '加油站',
            dataIndex: 'oilSiteName',
            render: text =>
                renderTableAdSelect({
                    props: this.props,
                    value: text,
                    key: allDictList.saleCompany,
                }),
        },
        {
            title: '附件',
            dataIndex: 'attaQuantity',
            width: 80,
            render: (text, record) =>
                text &&
                Number(text) > 0 && (
                    <Badge className="cus_badge" count={text}>
                        <div className="head-example">
                            <FileReader
                                type="list"
                                count={text}
                                urlType="tms"
                                params={{ bizId: record.id, fileBizType: 'OIL_MANA' }}
                            />
                        </div>
                    </Badge>
                ),
        },
        {
            title: '加油方式',
            dataIndex: 'oilType',
            render: text =>
                renderTableAdSelect({
                    props: this.props,
                    value: text,
                    key: allDictList.oilType,
                }),
        },

        {
            title: '当前里程(KM)',
            dataIndex: 'mileage',
        },
        {
            title: '加油量（L）',
            dataIndex: 'oilAmount',
        },
        {
            title: '单价',
            dataIndex: 'price',
            render: text => <span>{text && text !== 0 ? Number(text).toFixed(2) : 0}</span>,
        },
        {
            title: '币种',
            dataIndex: 'currencyType',
            render: text =>
                renderTableAdSelect({
                    props: this.props,
                    value: text,
                    key: allDictList.currencyType,
                }),
            width: 100,
        },
        {
            title: '金额',
            dataIndex: 'totalFee',
            render: text => <span>{text && text !== 0 ? Number(text).toFixed(2) : 0}</span>,
        },
        {
            title: '油耗',
            dataIndex: 'avgHundredConsump',
        },
        {
            title: '加油人',
            dataIndex: 'oilPerson',
        },
        {
            title: '账单号',
            dataIndex: 'billNo',
        },
        {
            title: '创建人',
            dataIndex: 'createBy',
            render: text => (
                <AdSearch
                    label="loginName"
                    name="sysName"
                    value={this.props.searchValue[text]}
                    onlyRead={true}
                />
            ),
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
        },
        {
            title: '更新人',
            dataIndex: 'updateBy',
            render: text => (
                <AdSearch
                    label="loginName"
                    name="sysName"
                    value={this.props.searchValue[text]}
                    onlyRead={true}
                />
            ),
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
        },
    ];

    onRef = ref => {
        this.child = ref;
    };

    getSelectList = val => {
        const { dispatch, searchValue } = this.props;
        let params = val || {};
        dispatch({
            type: 'tmsOil/selectList',
            payload: params,
            callback: data => {
                let valueList = [];
                data.map(v => {
                    if (!data) return;
                    const labels = ['updateBy', 'createBy'];
                    labels.map(item => {
                        if (v[item] && !valueList.includes(v[item])) {
                            valueList.push(v[item]);
                            !searchValue[v[item]] &&
                                dispatch({
                                    type: 'component/querySearchValue',
                                    payload: { params: { loginName: v[item] }, url: 'tms/tms-oil/selectOilUser_s' },
                                });
                        }
                    });
                });
            },
        });
    };

    //重置
    handleFormReset = () => {
        const { form, dispatch } = this.props;
        form.resetFields();
        this.setState({
            formValues: {},
            cars: [],
            billNos: [],
        });
        this.getSelectList();
    };

    toggleForm = expandForm => {
        this.setState({
            expandForm,
        });
    };

    //查询
    handleSearch = values => {
        // if (!values) {
        //   return;
        // }

        const { oilTime, settlementDate, ...value } = values;
        const { cars, billNos } = this.state;
        if (cars.length > 0) {
            const vehicleId = cars.map(v => {
                return v.id;
            });
            value.vehicleId = vehicleId.join(',');
        } else {
            value.vehicleId = '';
        }
        if (billNos.length > 0) {
            const billId = billNos.map(v => {
                return v.id;
            });
            value.billId = billId.join(',');
        } else {
            value.billId = '';
        }
        if (settlementDate)
            value.settlementDate = settlementDate ? moment(settlementDate).format(dateFormatByM) : '';
        if (oilTime&&oilTime.length>0) {
            value.oilStartTime = moment(oilTime[0]).format(dateFormat);
            value.oilEndTime = moment(oilTime[1]).format(dateFormat);
        }else{
            value.oilStartTime = ''
            value.oilEndTime = ''
        }
        this.setState({
            formValues: value,
        });
        this.getSelectList(value);
    };

    //新建
    handleAdd = () => {
        const { dispatch } = this.props;
        router.push(`/carDaily/oilList/add-form`);
    };
    //编辑：
    handleEdit = () => {
        router.push(`/carDaily/oilList/edit-form/${this.state.checkId}`);
        this.closeDetail();
    };
    // 分页操作：改参数
    handleStandardTableChange = param => {
        const { dispatch } = this.props;
        const { formValues } = this.state;
        const params = {
            ...formValues,
            ...param,
        };

        this.getSelectList(params);
    };

    //详情：
    showDetail = ( id, record) => {
        // e.stopPropagation();
        const { dispatch } = this.props;
        const status = record.billStatus ? record.billStatus : record.status;
        const isBillStatus = status === 'CONFIRM' || status === 'WAIT';
        dispatch({
            type: 'tmsOil/selectDetails',
            payload: { id },
        });
        // dispatch({
        //   type: 'tmsOil/viewPapersDetails',
        //   payload: { id: id },
        // });
        this.setState(
            {
                checkId: id,
                isBillStatus,
                detailsStatus: record.status,
            },
            () => {
                this.setState({
                    visible: true,
                });
            }
        );
    };

    closeDetail = () => {
        this.setState({
            visible: false,
        });
    };

    //启用、禁用：
    useVehicleType = type => {
        const { dispatch } = this.props;
        const { checkIds } = this.state;
        let urlType = 'tmsOil/enableDriver';
        if (type == 'disabled') {
            urlType = 'tmsOil/disabledDriver';
        }
        dispatch({
            type: urlType,
            payload: { ids: checkIds },
            callback: res => {
                prompt({ content: res.message });
            },
        });
    };
    getValue = (values, type) => {
        this.setState({
            [type]: values,
        });
    };

    handleSelectRows = selectedRows => {
        this.setState({
            selectedRows,
        });
    };

    /**
     * 生成账单
     */
    generatedBills = () => {
        const { dispatch } = this.props;
        const { selectedRows, formValues } = this.state;
        const checkBill = this.checkBill();
        if (!checkBill) return;
        dispatch({
            type: 'tmsOil/generatedBills',
            payload: { ids: selectedRows.map(v => v.id) },
            callback: data => {
                if (!data) return;
                this.setState({
                    selectedRows: [],
                });
                this.getSelectList(formValues);
                //跳转到账单的编辑页面
                router.push(`/carAccount/billList/editBill/${data}`);
            },
        });
    };

    /**
     * 生成账单校验 状态已提交，同一公司，同一加油方式
     */

    checkBill = () => {
        const { selectedRows } = this.state;
        const ownCompanyName = vitifyCheck({
            selectedRows,
            key: 'ownCompanyName',
            warn: '所选记录必须所属公司相同！',
        });
        if (!ownCompanyName) return false;
        const oilType = vitifyCheck({
            selectedRows,
            key: 'oilType',
            warn: '加油方式不同，不能合并生成帐单！',
        });
        if (!oilType) return false;
        if (oilType[0] === '月结') {
            const oilSiteName = vitifyCheck({
                selectedRows,
                key: 'oilSiteName',
                warn: '月结加油，加油站名称必须相同！',
            });
            if (!oilSiteName) return false;
        }
        return true;
    };
    //刷新油耗
    refreshOil = () =>{
        const { checkId } = this.state;
        const { dispatch } = this.props
        console.log('ceshi')
        let id = checkId
        dispatch({
            type:'tmsOil/refreshOil',
            payload:{id:checkId},
            callback:(res)=>{
                console.log('refreshOil===res=====',res)
                this.showDetail(id)
            }
        })
    }
    //删除加油
    removeRecord = () => {
        const { dispatch } = this.props;
        const { checkId, visible, formValues } = this.state;
        confirm({
            title: '确定要删除这条数据吗？',
            content: ' ',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: () => {
                dispatch({
                    type: 'tmsOil/deleteOil',
                    payload: { id: checkId },
                    callback: () => {
                        this.setState({ visible: false, selectedRows: [] });
                        this.getSelectList(formValues);
                    },
                });
            },
        });
    };
    //导入
    handleImportFile = () => {
        this.setState((pre) => ({
            visibleFile: !pre.visibleFile
        }));
    };
    //确认加油：
    oilConfirm = flag => {
        const { dispatch } = this.props;
        const { checkId, selectedRows, formValues } = this.state;
        const checked = selectedRows.some(v => {
            if (v.status !== 'WAIT') {
                return true;
            } else {
                return false;
            }
        });
        if (checked) {
            prompt({ title: '温馨提示', content: '请选择状态为待确认的加油记录', type: 'warn' });
            return;
        }

        dispatch({
            type: 'tmsOil/oilConfirm',
            payload: { ids: flag ? [checkId] : selectedRows.map(v => v.id) },
            callback: () => {
                this.setState({ selectedRows: [], detailsStatus: 'CONFIRM' });
                this.getSelectList(formValues);
            },
        });
    };

    selectAll = () => {
        const { dispatch } = this.props;
        const { formValues } = this.state;
        dispatch({
            type: 'tmsOil/selectAll',
            payload: formValues,
            callback: data => {
                this.setState({
                    selectedRows: [],
                });

                if (!data) return;
                this.getSelectList(formValues);
                //跳转到账单的编辑页面
                router.push(`/carAccount/billList/editBill/${data}`);
            },
        });
    };
    render() {
        const {
            form,
            loading,
            tmsOil: { selectList, carList },
            isMobile,
            ownCompany,
            searchValue,
            dictObject,
        } = this.props;
        // console.log('==========', codes);
        const { getFieldDecorator } = form;
        const {
            updateModalVisible,
            stepFormValues,
            visible,
            checkId,
            expandForm,
            selectedRows,
            formValues,
            isBillStatus,
            visibleFile,
            detailsStatus,
            isRefresh,
        } = this.state;
        const firstFormItem = (
            <FormItem label="单据号">
                {getFieldDecorator('oilNo')(<Input placeholder="请输入单据号" />)}
            </FormItem>
        );
        const commonParams = {
            getFieldDecorator,
        };
        const secondFormItem = (
            <AntdFormItem label="状态" code="billStatus" {...commonParams}>
                <AdSelect data={oilBillStateList} isExist={true} mode="multiple" />
            </AntdFormItem>
        );

        // secondForm 参数
        const otherFormItem = [
            [
                <FormItem label="车牌号">
                    {getFieldDecorator('vehicleId')(
                        <SearchSelect
                            dataUrl="tms/tms-oil/selectOilVehicle"
                            url="tms/tms-oil/selectOilVehicleView_s" // selectedData只只有id时需要传url
                            selectedData={this.state.cars} // 选中值
                            multiple={false} // 是否多选
                            showValue="cartPlateOneNo"
                            searchName="cartPlate"
                            columns={columns1} // 表格展示列
                            onChange={values => this.getValue(values, 'cars')} // 获取选中值
                            scrollX={480}
                            id="tmsOil_1"
                            allowClear={true}
                        />
                    )}
                </FormItem>,
            ],
            [
                <FormItem label="所属公司">
                    {getFieldDecorator('ownCompanyId')(
                        <Select
                            allowClear={true}
                            showSearch
                            filterOption={(input, option) =>
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            placeholder="请选择"
                            style={{ width: '100%' }}
                        >
                            <Option value="">请选择</Option>
                            {ownCompany.map((v, i) => {
                                return (
                                    <Option key={i} value={v.customerCode}>
                                        {v.customerName}
                                    </Option>
                                );
                            })}
                        </Select>
                    )}
                </FormItem>,
                <FormItem label="加油时间">
                    {getFieldDecorator('oilTime')(<AntdDatePicker mode="range" />)}
                </FormItem>,
                <AntdFormItem label="加油方式" code="oilType" {...commonParams}>
                    <AdSelect isExist={true} data={dictObject[allDictList.oilType]} />
                </AntdFormItem>,
            ],
            [
                <FormItem label="加油人">
                    {getFieldDecorator('oilPerson')(<Input placeholder="请输入加油人" />)}
                </FormItem>,
                <FormItem label="加油站">
                    {getFieldDecorator('oilSiteName')(
                        //   <Input placeholder="请输入加油站" />
                        <Select allowClear={true} showSearch placeholder="请选择">
                            <Option value="">请选择</Option>
                            {dictObject[allDictList.saleCompany] &&
                                dictObject[allDictList.saleCompany].map(item => (
                                    <Option key={item.code}>{item.value}</Option>
                                ))}
                        </Select>
                    )}
                </FormItem>,
                <FormItem label="账单号">
                    {getFieldDecorator('billId')(
                        <SearchSelect
                            dataUrl="tms/tms-oil/selectTmsBillList_s"
                            selectedData={this.state.billNos} // 选中值
                            multiple={false} // 是否多选
                            showValue="billNo"
                            searchName="billNo"
                            columns={columnsBillNo} // 表格展示列
                            onChange={values => this.getValue(values, 'billNos')} // 获取选中值
                            scrollX={200}
                            id="tmsOil_2"
                            allowClear={true}
                            payload={{ type: 'OIL' }}
                        />
                    )}
                </FormItem>,
            ],
            [
                // <FormItem label="行车档案号">
                //   {getFieldDecorator('archivesNo')(<Input placeholder="请输入行车档案号" />)}
                // </FormItem>,
                <FormItem label="结算周期" >
                    {/* {getFieldDecorator('archivesNo')(<MonthPicker style={{ width: "100%" }} />)} */}
                    {getFieldDecorator('settlementDate')(<MonthPicker style={{ width: "100%" }} />)}
                </FormItem>,

            ],
            ['operatorButtons'],
        ];
        const selectFormParams = {
            firstFormItem,
            secondFormItem,
            otherFormItem,
            form,
            code: codes.select,
            className: this.className,
            handleFormReset: this.handleFormReset,
            handleSearch: this.handleSearch,
            toggleForm: this.toggleForm,
        };
        const tableButtonsParams = {
            show: true,
            code: codes.add,
            handleAdd: this.handleAdd,
            selectedLength: selectedRows.length,
            pagination: selectList.pagination,
            selectAll: this.selectAll,
            code: codes.bill,
            buttons: (
                <Button.Group>
                    <AdButton
                        disabled={!selectedRows.length > 0}
                        onClick={() => this.oilConfirm()}
                        text="确认"
                        code={codes.confirm}
                    />
                    <AdButton onClick={() => this.handleImportFile()} text="导入" code={codes.import} />
                    <AdButton
                        disabled={!selectedRows.length > 0}
                        onClick={() => this.generatedBills()}
                        text={`生成账单${selectedRows.length > 0 ? '(' + selectedRows.length + ')' : ''}`}
                        code={codes.bill}
                    />
                </Button.Group>
            ),
        };

        const rightDrawParams = {
            isMobile,
            visible,
            title: '加油详情',
            code: codes.showDetail,
            closeDetail: this.closeDetail,
            buttons: (
                <span>
                    <AdButton 
                        onClick={() => this.refreshOil()}
                        disabled={!isBillStatus}
                        text="刷新油耗"
                        type="primary"
                        ghost
                        code={codes.remove}
                    />
                    <AdButton 
                        onClick={() => this.removeRecord(1)}
                        disabled={!isBillStatus}
                        text="删除"
                        type="danger"
                        ghost
                        code={codes.remove}
                    />
                    <Button.Group style={{ marginLeft: 8 }}>
                        <AdButton
                            disabled={!isBillStatus || detailsStatus !== 'WAIT'}
                            onClick={() => this.oilConfirm(1)}
                            text="确认"
                            code={codes.confirm}
                        />
                        <AdButton
                            disabled={!isBillStatus}
                            onClick={this.handleEdit}
                            text="编辑"
                            type="primary"
                            code={codes.edit}
                        />
                    </Button.Group>
                </span>
            ),
        };

        const billStatus = formValues.billStatus;
        const disabledRowSelected =
            billStatus && billStatus.length === 1 && billStatus.includes('CONFIRM') ? false : true;

        return (
            <Fragment>
                <FileImport
                    visibleFile={visibleFile}
                    handleCancel={() => {
                        this.handleImportFile();
                    }}
                    urlImport={`tms/tms-oil/importOil`}
                    urlCase={`attachment/加油导入模板.xlsx`}
                    queryData={[this.getSelectList]}
                    accept=".xls,.xlsx"
                />
                <SelectForm {...selectFormParams} />
                <TableButtons {...tableButtonsParams} />
                <StandardTable
                    loading={loading}
                    selectedRows={selectedRows}
                    data={selectList}
                    disabledSelectedRows={{ code: ['billStatus', 'status'], value: ['CONFIRM', 'WAIT'] }}
                    columns={this.columns}
                    onSelectRow={this.handleSelectRows}
                    onPaginationChange={this.handleStandardTableChange}
                    expandForm={expandForm}
                    className={this.className}
                    code={codes.page}
                    getCheckboxProps={record => {
                        const status = record.billStatus ? record.billStatus : record.status;
                        const checked = status === 'CONFIRM' || status === 'WAIT';
                        return !checked;
                    }}
                />
                <RightDraw {...rightDrawParams}>
                    <OilTetails type="details" checkId={checkId} isMobile={isMobile} 
                        isRefresh={isRefresh}
                    />
                </RightDraw>
            </Fragment>
        );
    }
}
